<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="formIs"
      class="bg-bg_color w-[99/100] pl-8 pt-4"
    >
      <!-- <el-form-item label="角色名称：" prop="name">
        <el-input
          v-model="formIs.admin_name"
          placeholder="请输入角色名称"
          clearable
          class="!w-[200px]"
        />
      </el-form-item> -->
      <el-form-item label="角色名称：" prop="code">
        <el-input
          v-model="formIs.role_id"
          placeholder="请输入角色名称"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <!-- <el-form-item label="状态：" prop="status">
        <el-select
          v-model="formIs.admin_status"
          placeholder="请选择状态"
          clearable
          class="!w-[180px]"
        >
          <el-option label="已开启" value="0" />
          <el-option label="已关闭" value="1" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch(formIs.role_id)"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar title="角色列表" @refresh="onSearch">
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="addUserAdmin()"
          v-auth="'role_add'"
        >
          新增角色
        </el-button>
      </template>
      <template v-slot="{ size, checkList }">
        <pure-table
          border
          ref="waterRef"
          :row-key="formIs.role_id"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="
            dataList.slice(
              (pagination.currentPage - 1) * pagination.pageSize,
              pagination.currentPage * pagination.pageSize
            )
          "
          :columns="columns"
          :checkList="checkList"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @selection-change="handleSelectionChange"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="handleUpdateUser(row)"
              v-auth="'role_modify'"
            >
              修改
            </el-button>
            <el-popconfirm title="是否确认删除?" @confirm="handleDelete(row)">
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                  v-auth="'role_delete'"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="handleAddroute(row)"
              v-auth="'role_allocation'"
            >
              分配路由
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <el-dialog v-model="dialogFormVisible" title="添加/编辑角色">
      <el-form :model="formIs">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input
            @input="handleInput"
            v-model="formIs.role_name"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth">
          <el-input v-model="formIs.role_desc" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false" type="danger"
            >取消</el-button
          >
          <el-button type="primary" @click="handleSubmit()"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogRoute" title="分配路由">
      <el-tree-v2
        ref="treeRef"
        :data="menus"
        :props="dataProps"
        :height="500"
        show-checkbox
        :filter-method="filterMethod"
        :check-strictly="true"
        @check="handleTreeCheck"
        :default-checked-keys="defaultCheckedKeys"
      >
        <template #default="{ data }">
          <span>{{ transformI18n(data.title) }}</span>
        </template>
      </el-tree-v2>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogRoute = false" type="danger">取消</el-button>
          <el-button type="primary" @click="handleRouteSubmit()">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, inject, onMounted } from "vue";
import { useRole } from "./hook";
import type { ElTreeV2 } from "element-plus";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getRoleList, getRoleUpdate } from "@/api/user";
import { message } from "@/utils/message";
import * as CryptoJS from "crypto-js";
import { transformI18n } from "@/plugins/i18n";
import { storageSession } from "@pureadmin/utils";
import { getSessionKey } from "@/utils/auth";
import {
  getAsyncAllRoutes,
  updateAsyncRoutes,
  roleList,
  addRoleInsert,
  updateRole,
  roleAssign
} from "@/api/routes";
import { getRoleInfo } from "@/api/user";
import { useUserStoreHook } from "@/store/modules/user";
import type { TreeNode } from "element-plus/es/components/tree-v2/src/types";
// import Database from "@iconify-icons/ri/database-2-line";
// import More from "@iconify-icons/ep/more-filled";
import Refresh from "@iconify-icons/ep/refresh";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Search from "@iconify-icons/ep/search";
// import Menu from "@iconify-icons/ep/menu";
import AddFill from "@iconify-icons/ri/add-circle-line";

defineOptions({
  name: "Administrators"
});
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
interface treeNode extends TreeNode {
  meta: {
    title: string;
  };
}
interface FormType {
  role_name: string;
  role_desc: string;
  role_id: string;
}
const isEdit = ref("");
const refresh: any = inject("reload");
const dialogFormVisible = ref(false);
const formRef = ref();
const menus = ref([]);
const adminId = ref(false);
const waterRef = ref();
const dialogRoute = ref(false);
const formLabelWidth = "100px";
const roleId = ref("");
const roleName = ref("");
const checkedKeys = ref([]);
const formIs = reactive<FormType>({
  role_id: "",
  role_name: "",
  role_desc: ""
});
const dataProps = ref({
  value: "route_id",
  children: "children",
  label: "title"
});
const formIsRef = ref({});
const {
  loading,
  columns,
  dataList,
  pagination,
  // buttonClass,
  onSearch,
  resetForm,
  // handleUpdate,
  handleDelete,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange
} = useRole(waterRef);
function handleUpdateUser(row) {
  formIs.role_id = row.role_id;
  formIs.role_name = row.role_name;
  formIs.role_desc = row.role_desc;
  adminId.value = true;
  isEdit.value = 1;
  dialogFormVisible.value = true;
}
//新增按钮
function addUserAdmin() {
  adminId.value = false;
  formIs.role_name = "";
  formIs.role_desc = "";
  const roleId = getSessionKey().role_id;
  // handleUserList(roleId);
  isEdit.value = 0;
  dialogFormVisible.value = true;
}
//获取角色列表
async function handleUserList(roleId) {
  const role = {
    role: roleId
  };

  const roleJson = JSON.stringify(role);
  const roleBase64 = CryptoJS.enc.Base64.stringify(
    CryptoJS.enc.Utf8.parse(roleJson)
  );
  const roleValue = {
    value: roleBase64
  };
  const res = await getRoleList(roleValue);
  if (res.code === 200) {
    message(res.msg, { type: "success" });
  } else {
    message(res.msg, { type: "error" });
  }
}
const handleInput = value => {
  // 使用正则表达式匹配只有字母和数字的字符串
  const regex = /^[a-zA-Z0-9]+$/;
  if (!regex.test(value)) {
    // 如果输入的值不符合正则表达式，则将inputValue重置为上一个合法的值
    formIs.role_name = value.replace(/[^a-zA-Z0-9]/g, "");
  }
};
//新增/修改角色
async function handleSubmit() {
  if (isEdit.value == 0) {
    if (formIs.role_name === "") {
      message("请输入角色名称", { type: "error" });
      return false;
    }
    if (formIs.role_desc === "") {
      message("请输入角色描述", { type: "error" });
      return false;
    }
    formIsRef.value = formIs;
    console.log(formIs);
    // 将formIsRef.value对象转换为JSON字符串
    const formIsRefStr = JSON.stringify(formIsRef.value);
    const res = await addRoleInsert(formIsRefStr);
    if (res.code === 200) {
      message("添加角色成功", { type: "success" });
      dialogFormVisible.value = false;
      dialogFormVisible.value = true;
      refresh();
    } else {
      dialogFormVisible.value = true;
      message(res.msg, { type: "error" });
    }
  } else {
    formIsRef.value = formIs;
    const formIsRefStr = JSON.parse(JSON.stringify(formIsRef.value));
    const obj = {
      ...formIsRefStr
    };
    updateRole(obj).then(res => {
      if (res.code == 200) {
        dialogFormVisible.value = false;
        message("修改角色成功", { type: "success" });
        getRouteList();
      } else {
        message(res.msg, { type: "error" });
      }
    });
    console.log("32342342300888", formIsRefStr);
  }
}
//获取路由列表
const getRouteList = async () => {
  const res = await getAsyncAllRoutes();
  menus.value = res.data;
  console.log(res);
};
const filterMethod = (query: string, node: treeNode) => {
  return transformI18n(node.title)!.indexOf(query) !== -1;
};
//分配路由
async function handleAddroute(row) {
  roleId.value = row.role_id;
  roleName.value = row.role_name;
  // const formIsRefStr = JSON.stringify({
  //   role_id: row.role_id
  // });

  // 对JSON字符串进行Base64加密
  // const encryptedFormIsRef = CryptoJS.enc.Base64.stringify(
  //   CryptoJS.enc.Utf8.parse(formIsRefStr)
  // );
  // const encryptedFormIsRefValue = {
  //   value: encryptedFormIsRef
  // };

  const obj = {
    roleId: roleId.value
  };
  console.log(obj, "===--");
  const res = await getRoleInfo(obj);
  if (res.code === 200) {
    checkedKeys.value = res.data.group;
    setTimeout(() => {
      treeRef.value.setCheckedKeys(checkedKeys.value);
    }, 100);
    dialogRoute.value = true;
  } else {
    message(res.msg, { type: "error" });
  }
}
//分配路由提交
const handleRouteSubmit = async () => {
  checkedKeys.value = treeRef.value.getCheckedKeys();
  console.log(checkedKeys.value);
  // const roleJson = JSON.stringify({
  //   role_id: roleId.value,
  //   role_name: roleName.value,
  //   route_list: checkedKeys.value.join(",")
  //     ? checkedKeys.value.join(",")
  //     : undefined
  // });
  // const roleBase64 = CryptoJS.enc.Base64.stringify(
  //   CryptoJS.enc.Utf8.parse(roleJson)
  // );
  // const roleValue = {
  //   value: roleBase64
  // };
  const parmas = {
    role_id: roleId.value,
    route_list: checkedKeys?.value.join(",")
  };
  const res = await roleAssign(parmas);
  if (res.code === 200) {
    const asyncRouteList = storageSession().getItem("user-info") as any;
    if (roleName.value == asyncRouteList.role_name) {
      // TODO: 执行登出操作
      useUserStoreHook().logOut();
    }
    dialogRoute.value = false;
    message(`分配权限${res.msg}`, { type: "success" });
  } else {
    message(res.msg, { type: "error" });
  }
};

const handleTreeCheck = (node, { checkedKeys }) => {
  console.log(checkedKeys, node);
  treeRef.value.setCheckedKeys(checkedKeys, false);
  // 获取当前节点的完整树节点对象
  const treeNode = treeRef.value.getNode(node.route_id);
  // console.log(treeNode);
  // 判断节点的层级
  if (treeNode.level === 3) {
    const parentNode = checkedKeys;
    // 如果是三级节点，先选中它本身，再选中它的所有父节点
    const checkParent = node => {
      if (node.parent) {
        parentNode.push(node.parent.key);
        checkParent(node.parent);
      }
    };
    checkParent(treeNode);
    treeRef.value.setCheckedKeys(parentNode, true);
  } else if (treeNode.level === 2) {
    if (checkedKeys.includes(treeNode.key)) {
      // treeNode.key 在 checkedKeys 中
      console.log("选中");
    } else {
      // treeNode.key 不在 checkedKeys 中
      const checked = [];
      treeNode.children.forEach(item => {
        checked.push(item.key);
      });
      checkedKeys = checkedKeys.filter(item => {
        return !checked.includes(item);
      });
      treeRef.value.setCheckedKeys(checkedKeys, true);
      console.log("取消选中");
    }
  } else if (treeNode.level === 1) {
    if (checkedKeys.includes(treeNode.key)) {
      // treeNode.key 在 checkedKeys 中
      console.log("选中");
    } else {
      // treeNode.key 不在 checkedKeys 中
      const checked = [];
      const traverse = (node, checked) => {
        if (node.children) {
          node.children.forEach(child => {
            checked.push(child.key);
            traverse(child, checked);
          });
        }
      };
      traverse(treeNode, checked);
      // treeNode.children.forEach(item => {
      //   checked.push(item.key);
      // });
      console.log(checked);
      checkedKeys = checkedKeys.filter(item => {
        return !checked.includes(item);
      });
      treeRef.value.setCheckedKeys(checkedKeys, true);
      console.log("取消选中");
    }
  }
};

onMounted(() => {
  // getroleList();
  getRouteList();
});
</script>
<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
